package com.yinhe.music.yhmusic.main.my;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.dou361.dialogui.DialogUIUtils;
import com.dou361.dialogui.bean.BuildBean;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.yinhe.music.common.utils.DisplayUtil;
import com.yinhe.music.common.utils.JsonUtil;
import com.yinhe.music.common.utils.ScreenUtils;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.event.RxbusListObject;
import com.yinhe.music.event.RxbusNullObject;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.adapter.MyAdapter;
import com.yinhe.music.yhmusic.adapter.MyHeaderAdapter;
import com.yinhe.music.yhmusic.adapter.SongMenuContentAdapter;
import com.yinhe.music.yhmusic.album.TabActivity;
import com.yinhe.music.yhmusic.application.MusicApplication;
import com.yinhe.music.yhmusic.base.BasePresenter;
import com.yinhe.music.yhmusic.base.BaseServiceFragment;
import com.yinhe.music.yhmusic.cache.CacheManager;
import com.yinhe.music.yhmusic.collect.MyCollectionActivity;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.db.DataBaseAccessor;
import com.yinhe.music.yhmusic.db.bean.MenuDBEntity;
import com.yinhe.music.yhmusic.dialog.MenuManagerDialog;
import com.yinhe.music.yhmusic.downmusic.DownloadTask;
import com.yinhe.music.yhmusic.localmusic.view.LocalActivity;
import com.yinhe.music.yhmusic.login.LoginRegisterActivity;
import com.yinhe.music.yhmusic.main.BoughtMusicActivity;
import com.yinhe.music.yhmusic.model.LoginInfo;
import com.yinhe.music.yhmusic.model.Music;
import com.yinhe.music.yhmusic.model.MyTitleItem;
import com.yinhe.music.yhmusic.model.SongMenuList;
import com.yinhe.music.yhmusic.model.UserInfo;
import com.yinhe.music.yhmusic.radio.MyCollectRadioActivity;
import com.yinhe.music.yhmusic.recent.RecentPlayActivity;
import com.yinhe.music.yhmusic.songmenu.MenuManagerActivity;
import com.yinhe.music.yhmusic.songmenu.SongMenuActivity;
import com.yinhe.music.yhmusic.songmenu.SongMenuListActivity;
import com.yinhe.music.yhmusic.utils.DataHolder;
import com.yinhe.music.yhmusic.utils.Preferences;
import com.yinhe.music.yhmusic.widget.DividerItemDecoration;
import com.yinhe.music.yhmusic.widget.MyItemDecoration;
import com.yinhe.music.yhmusic.widget.MyMusicDecoration;
import com.yinhe.music.yhmusic.widget.RecmmendItemDecoration;
import com.yinhe.music.yhmusic.widget.WrapContentLinearLayoutManager;

import java.util.List;

import butterknife.BindView;

/**
 * 我的界面
 *
 * @author hasee
 * @date 2017/8/23
 */

public class MyMusicFragment extends BaseServiceFragment implements BaseQuickAdapter.OnItemClickListener,
        View.OnClickListener, MyContract.IMyView {

    @BindView(R.id.recommend_music_recyclerview)
    RecyclerView recyclerview;

    private MyHeaderAdapter headAdapter;
    private MyAdapter mAdapter;
    private MyMusicDecoration itemDecoration;
    private MyPresenter mPresenter;

    public static MyMusicFragment newInstance() {
        Bundle args = new Bundle();
        MyMusicFragment fragment = new MyMusicFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public BasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    public void initPresenter() {
        mPresenter = new MyPresenter();
        mPresenter.attachModelView(new MyModel(), this);
    }

    @Override
    public void initView() {
        RxBus.get().register(this);
        initAdapter();
        initMenuList();
    }

    private void initMenuList() {
        if (Preferences.getLoginSn().isEmpty()) {
            mPresenter.getLocalVisitorData();
        } else {
            mPresenter.getUserInfo();
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.recycler_layout;
    }

    private void initAdapter() {
        mAdapter = new MyAdapter(mPresenter.getLocalMenuData());
        mAdapter.addHeaderView(initHeadView(recyclerview));

        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> mPresenter.getShowMoreData(position, adapter));

        recyclerview.setFocusable(false);
        recyclerview.setAdapter(mAdapter);
        recyclerview.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));
        //关闭recyclerView自带动画
        ((SimpleItemAnimator) recyclerview.getItemAnimator()).setSupportsChangeAnimations(false);
        mAdapter.expandAll();
    }


    @Override
    public void onDestroyView() {
        RxBus.get().unregister(this);
        super.onDestroyView();
    }

    @Override
    public void setUserUI(UserInfo userInfo) {
        setLocalMusicSize();
        setDownMusicSize();
        setRecentMusicSize();
        if (userInfo != null) {
            headAdapter.getData().get(4).setCount(userInfo.getCollectRadioNum());
            headAdapter.getData().get(3).setCount(userInfo.getCollectNum());
            headAdapter.getData().get(5).setCount(userInfo.getPurchaseSongNum());


            if (userInfo.getVipLevel() == 0) {
                Preferences.setIsVip(false);
            } else {
                Preferences.setIsVip(true);
            }

            headAdapter.notifyDataSetChanged();

            mPresenter.parseData(userInfo);
        }
    }

    @Override
    public void setMenuUI(List<MultiItemEntity> menuItem) {
        mAdapter.setNewData(menuItem);
        setItemDecoration();
        mAdapter.expandAll();
    }

    @Override
    public void setLocalMenuUI(List<MultiItemEntity> menuItem) {
        mAdapter.setNewData(menuItem);
        mAdapter.expandAll();
    }

    /**
     * 设置推荐歌单列表
     *
     * @param songMenuLists 歌单列表
     * @return recyclerview
     */
    private View getRecommendView(List<SongMenuList> songMenuLists) {
        View view = getLayoutInflater().inflate(R.layout.home_page_recycler_layout, (ViewGroup) recyclerview.getParent(), false);

        RecyclerView recyclerView = view.findViewById(R.id.recycler_view);
        TextView text = view.findViewById(R.id.head_text);
        TextView more = view.findViewById(R.id.more_text);
        View space = view.findViewById(R.id.space);

        space.setVisibility(View.VISIBLE);
        text.setText(R.string.recommend_menu);
        recyclerView.setFocusable(false);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };

        recyclerView.addItemDecoration(new RecmmendItemDecoration(getActivity(), 8));
        recyclerView.setLayoutManager(gridLayoutManager);
        SongMenuContentAdapter songMenuAdapter = new SongMenuContentAdapter(songMenuLists);
        recyclerView.setAdapter(songMenuAdapter);

        more.setOnClickListener(this);
        songMenuAdapter.setOnItemClickListener(this);

        return view;
    }

    @Override
    public void showManagerDialog(List<SongMenuList> menuList, int type) {
        MenuManagerDialog aDialog = new MenuManagerDialog(getActivity(), type, new MenuManagerDialog.MenuManagerDialogListener() {
            @Override
            public void menuManagerDialogDidManager(BuildBean dialog) {
                if (Preferences.getLoginSn().isEmpty()) {
                    startLogin();
                    return;
                }
                Intent intent = new Intent(getContext(), MenuManagerActivity.class);
                intent.putExtra("menuType", type);
                DataHolder.getInstance().setData(menuList);
                startActivity(intent);
                DialogUIUtils.dismiss(dialog);
            }

            @Override
            public void menuManagerDialogDidCreate(String mName, BuildBean dialog) {
                mPresenter.createSongMenu(mName, null, IConstants.ONLINE);
                DialogUIUtils.dismiss(dialog);
            }
        });
        aDialog.show();
    }

    private View initHeadView(RecyclerView recyclerView) {
        View view = getLayoutInflater().inflate(R.layout.recycler_layout, (ViewGroup) recyclerView.getParent(), false);
        RecyclerView headRecyclerView = view.findViewById(R.id.recommend_music_recyclerview);
        headRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));

        headAdapter = new MyHeaderAdapter(mPresenter.getHeaderData());
        headAdapter.addHeaderView(getLayoutInflater().inflate(R.layout.my_music_space, (ViewGroup) headRecyclerView.getParent(), false));
        headAdapter.setOnItemClickListener(this);

        headRecyclerView.setAdapter(headAdapter);
        headRecyclerView.addItemDecoration(new MyItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL_LIST, -1,
                ScreenUtils.dp2px(70)));
        return view;
    }

    /**
     * 设置分割线
     */
    private void setItemDecoration() {
        if (itemDecoration != null) {
            recyclerview.removeItemDecoration(itemDecoration);
        }
        MyTitleItem item = (MyTitleItem) mAdapter.getData().get(0);
        MyTitleItem item2 = (MyTitleItem) mAdapter.getData().get(1);
        int createSize = item.getSubItems() == null ? 0 : item.getSubItems().size();
        int collectSize = item2.getSubItems() == null ? 0 : item2.getSubItems().size();
        itemDecoration = new MyMusicDecoration(getActivity(), createSize, collectSize,
                DisplayUtil.dp2px(MusicApplication.getContext(), 70));
        recyclerview.addItemDecoration(itemDecoration);
    }

    /**
     * 更新本地歌曲数
     */
    private void setLocalMusicSize() {
        headAdapter.getData().get(0).setCount(CacheManager.getInstance().getScanMusic().size());
        headAdapter.notifyDataSetChanged();
    }

    /**
     * 更新下载歌曲数
     */
    private void setDownMusicSize() {
        headAdapter.getData().get(1).setCount((int) DataBaseAccessor.getInstance().getDownMusicCount());
        headAdapter.notifyDataSetChanged();
    }

    /**
     * 更新最近歌曲数
     */
    private void setRecentMusicSize() {
        headAdapter.getData().get(2).setCount((int) DataBaseAccessor.getInstance().getRecentCount());
        headAdapter.notifyDataSetChanged();
    }

    /**
     * 退出登录时重置歌曲数
     */
    private void clearData() {
        headAdapter.getData().get(2).clearCount();
        headAdapter.getData().get(3).clearCount();
        headAdapter.getData().get(4).clearCount();
        headAdapter.getData().get(5).clearCount();
        headAdapter.notifyDataSetChanged();
    }

    /**
     * 跳转本地歌曲界面
     */
    private void startLocal() {
        Intent localIntent = new Intent(getActivity(), LocalActivity.class);
        startActivity(localIntent);
    }

    /**
     * 跳转下载歌曲界面
     */
    private void startDownLoad() {
        Intent intent = new Intent(getActivity(), TabActivity.class);
        intent.putExtra("type", IConstants.DOWNLOAD_ACTIVITY);
        startActivity(intent);
    }

    /**
     * 跳转最近播放界面
     */
    private void startRecent() {
        startActivity(new Intent(getActivity(), RecentPlayActivity.class));
    }

    /**
     * 跳转我的收藏界面
     */
    private void startCollection() {
        if (!Preferences.getLoginSn().isEmpty()) {
            startActivity(new Intent(getActivity(), MyCollectionActivity.class));
            headAdapter.getData().get(3).setShowRedPoint(false);
            headAdapter.notifyDataSetChanged();
        } else {
            startActivity(new Intent(getActivity(), LoginRegisterActivity.class));
        }
    }

    /**
     * 跳转收藏的电台
     */
    private void startCollectRadio() {
        if (!Preferences.getLoginSn().isEmpty()) {
            startActivity(new Intent(getActivity(), MyCollectRadioActivity.class));
        } else {
            startActivity(new Intent(getActivity(), LoginRegisterActivity.class));
        }
    }

    /**
     * 跳转已购歌曲
     */
    private void startBoughtMusic() {
        if (Preferences.getLoginSn().length() > 0) {
            startActivity(new Intent(getActivity(), BoughtMusicActivity.class));
        } else {
            startActivity(new Intent(getActivity(), LoginRegisterActivity.class));
        }
    }

    /**
     * 推荐歌单跳转
     *
     * @param menuList 歌单信息
     */
    private void starRecommend(SongMenuList menuList) {
        Intent intent = new Intent(getActivity(), SongMenuActivity.class);
        intent.putExtra("menu", menuList);
        intent.putExtra("menuid", menuList.getSongMenuId());
        intent.putExtra("type", Music.Type.ONLINE);
        intent.putExtra("name", menuList.getSongMenuName());
        startActivity(intent);
    }

    /**
     * 头部点击事件
     *
     * @param position 位置
     */
    private void setHeadOnClick(int position) {
        switch (position) {
            case 0:
                startLocal();
                break;
            case 1:
                startDownLoad();
                break;
            case 2:
                startRecent();
                break;
            case 3:
                startCollection();
                break;
            case 4:
                startCollectRadio();
                break;
            case 5:
                startBoughtMusic();
                break;
            default:
                break;
        }
    }

    /**
     * 歌单点击事件
     *
     * @param item adapter item
     */
    private void setItemOnClick(MultiItemEntity item) {
        if (Preferences.getLoginSn().isEmpty()) {
            startActivity(new Intent(getActivity(), LoginRegisterActivity.class));
        } else {
            if (item.getItemType() == 1) {
                SongMenuList menu = (SongMenuList) item;
                Intent intent = new Intent(getActivity(), SongMenuActivity.class);
                intent.putExtra("menuid", menu.getSongMenuId());
                intent.putExtra("menu", menu);

                MyTitleItem titleItem = (MyTitleItem) mAdapter.getData().get(0);
                List<SongMenuList> createList = titleItem.getSubItems();

                if (createList.contains(menu)) {
                    intent.putExtra("type", Music.Type.LOCAL);
                } else {
                    intent.putExtra("type", Music.Type.ONLINE);
                }

                if (menu.getPrivateX() == 1) {
                    intent.putExtra("like", true);
                }

                if (menu.getPrivateX() == 2) {
                    intent.putExtra("editable", true);
                }
                startActivity(intent);
            }
        }


    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (adapter == headAdapter) {
            setHeadOnClick(position);
        } else if (adapter == mAdapter) {
            MultiItemEntity item = (MultiItemEntity) adapter.getItem(position);
            if (item != null) {
                setItemOnClick(item);
            }
        } else {
            SongMenuList menuList = (SongMenuList) adapter.getItem(position);
            starRecommend(menuList);
        }
    }

    /**
     * 更新下载/本地歌曲数
     *
     * @param downloadTask 下载任务
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxBusEventType.Download.DOWNLOAD_PAUSE),
                    @Tag(RxBusEventType.Download.DOWNLOAD_START),
                    @Tag(RxBusEventType.Download.DOWNLOAD_PROCESS),
                    @Tag(RxBusEventType.Download.DOWNLOAD_CANCEL),
                    @Tag(RxBusEventType.Download.DOWNLOAD_COMPLETE),
                    @Tag(RxBusEventType.Download.DOWNLOAD_ERROR)}
    )
    public void onRxbusDownloadEvent(DownloadTask downloadTask) {
        setLocalMusicSize();
        setDownMusicSize();
    }

    /**
     * 登录回调
     *
     * @param info 登录信息
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxBusEventType.User.LOGIN_SUCCESS),
                    @Tag(RxBusEventType.User.REGISTER_SUCCESS)}
    )
    public void onRxbusLoginEvent(LoginInfo info) {
        initMenuList();
    }

    /**
     * 登出回调
     *
     * @param rxbusNullObject {@link RxbusNullObject}
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.User.LOGOUT)
    )
    public void onRxbusLogoutEvent(RxbusNullObject rxbusNullObject) {
        clearData();
        initMenuList();
    }

    /**
     * 更新歌单信息回调
     *
     * @param rxbusNullObject {@link RxbusNullObject}
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxBusEventType.SongMenu.CREATE_MENU),
                    @Tag(RxBusEventType.SongMenu.ADD_MUSIC_TO_MENU),
                    @Tag(RxBusEventType.SongMenu.DELETE_MENU),
                    @Tag(RxBusEventType.SongMenu.COLLECT_MENU),
                    @Tag(RxBusEventType.Home.CHANGE_LANG_TYPE),
                    @Tag(RxBusEventType.SongMenu.DELETE_MENU_MUSIC),
                    @Tag(RxBusEventType.SongMenu.UPDATE_MENU_IMAGE),
                    @Tag(RxBusEventType.SongMenu.UPDATE_MENU_NAME)}
    )
    public void onRxbusUpdateMenu(RxbusNullObject rxbusNullObject) {
        mPresenter.getUserInfo();
    }

    /**
     * 删除歌曲时，更新最近歌曲数
     *
     * @param rxbusListObject {@link RxbusListObject}
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.Recent.DELETE_RECENT_MUSIC)
    )
    public void onRxbusDeleteRecentMusic(RxbusListObject rxbusListObject) {
        setRecentMusicSize();
    }

    /**
     * 播放歌曲时，更新最近歌曲数
     *
     * @param music 播放的歌曲
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.Recent.PLAY_MUSIC)
    )
    public void onRxbusDeleteRecentMusic(Music music) {
        setRecentMusicSize();
    }

    /**
     * 删除本地歌曲时，更新歌曲数
     *
     * @param rxbusListObject {@link RxbusListObject}
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.Local.DELETE_LOCAL_MUSIC)
    )
    public void onRxbusDeleteLocalMusic(RxbusListObject rxbusListObject) {
        if (rxbusListObject.rxList != null) {
            setLocalMusicSize();
            setDownMusicSize();
        }
    }

    /**
     * 删除下载歌曲时，更新歌曲数
     *
     * @param rxbusListObject {@link RxbusListObject}
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.Music.DELETE_DOWN_MUSIC)
    )
    public void onRxbusDeleteDownMusic(RxbusListObject rxbusListObject) {
        setDownMusicSize();
        setLocalMusicSize();
    }

    /**
     * 扫描本地歌曲时，更新歌曲数
     *
     * @param rxbusNullObject {@link RxbusNullObject}
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.Music.SCAN_MUSIC)
    )
    public void onRxbusScanMusic(RxbusNullObject rxbusNullObject) {
        if (CacheManager.getInstance().isLoadingSuccess()) {
            setLocalMusicSize();
        }
    }

    /**
     * 更新收藏数
     *
     * @param id 不需要用到
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxBusEventType.Radio.COLLECT_RADIO),
                    @Tag(RxBusEventType.Album.COLLECT_ALBUM),
                    @Tag(RxBusEventType.Mv.UPDATA_COLLECT_NUM),
                    @Tag(RxBusEventType.Singer.COLLECT_SINGER),
                    @Tag(RxBusEventType.Music.BUY_MUSIC)}
    )
    public void onRxbusUpdateItemNum(String id) {
        mPresenter.getUserInfo();
    }

    /**
     * 更新歌单信息回调
     *
     * @param menuDBEntity 歌单信息
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.SongMenu.UPDATE_MENU)
    )
    public void onRxbusUpdateLocalMenu(MenuDBEntity menuDBEntity) {
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(getActivity(), SongMenuListActivity.class);
        startActivity(intent);
    }
}
